package org.wang.generalcode.modules.exam.listener;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.apache.commons.lang3.StringUtils;
import org.wang.generalcode.modules.exam.constants.EnumConstants;
import org.wang.generalcode.modules.exam.pojo.entity.QuestionInfoEntity;

import java.util.ArrayList;
import java.util.List;

public class ExcelListener extends AnalysisEventListener<QuestionInfoEntity> {
    private List<QuestionInfoEntity> successList = new ArrayList<>();
    private List<QuestionInfoEntity> failList = new ArrayList<>();
    private String errorMsg = "";

    @Override
    public void invoke(QuestionInfoEntity data, AnalysisContext context) {

        String errorMsg = customValidation(data);
        if (StringUtils.isNotEmpty(errorMsg)) {
            failList.add(data);
            return;
        }

        // 校验试题类型是否合法
        String questionTypeName = data.getQuestionTypeName();
        boolean flag = false;
        for (EnumConstants.QuestionType value : EnumConstants.QuestionType.values()) {
            if (value.getName().equals(questionTypeName)) {
                flag = true;
                break;
            }
        }
        if (!flag) {
            errorMsg = "试题类型不正确";
            failList.add(data);
            return;
        }

        successList.add(data);
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 所有数据解析完成后的操作
    }

    public List<QuestionInfoEntity> getSuccessList() {
        return successList;
    }

    public List<QuestionInfoEntity> getFailList() {
        return failList;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    private String customValidation(QuestionInfoEntity questionInfo) {
        // 自定义验证逻辑
        if (questionInfo == null) {
            return "问题信息不能为空";
        }
        if (StringUtils.isBlank(questionInfo.getContent())) {
            return "问题内容不能为空";
        }
        if (StrUtil.isEmptyIfStr(questionInfo.getQuestionTypeName())) {
            return "问题类型不能为空";
        }
        // 其他验证逻辑...
        return null; // 验证通过
    }
}
